<template>
  <el-dialog title="新增协同任务" :close-on-click-modal="false" :close-on-press-escape="false"
             :visible.sync="visible" lock-scroll class="wpwork-dialog wpwork-dialog_center" width="600px">
    <el-form ref="dataForm" v-loading="formLoading" :model="dataForm" :rules="dataRule"
             label-width="100px" class="menuForm">
      <wpwork-form-tip-item label="任务标题" prop="taskTitle">
        <el-input v-model="dataForm.taskTitle" placeholder="输入任务标题" />
      </wpwork-form-tip-item>

      <wpwork-form-tip-item label="任务内容" prop="taskContent">
        <el-input type="textarea" v-model="dataForm.taskContent" placeholder="输入任务内容" />
      </wpwork-form-tip-item>

      <wpwork-form-tip-item label="任务有效期" prop="timeRange">
        <el-date-picker
          v-model="dataForm.timeRange"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          value-format="yyyy-MM-dd HH:mm:ss"
          style="width: 100%">
        </el-date-picker>
      </wpwork-form-tip-item>

      <wpwork-form-tip-item label="任务参与人" prop="participants">
        <el-select
          v-model="dataForm.participants"
          placeholder="请选择任务参与人"
          multiple
          clearable
          readonly
          @focus="openUserBindPanel">
          <el-option
            v-for="user in dataForm.participants"
            :key="user.id"
            :label="user.realName"
            :value="user.id">
<!--            <span style="float: left">{{ user.realName }}</span>-->
<!--            <span style="float: right; color: #8492a6; font-size: 13px">-->
<!--              {{ user.type === 'person' ? '个人' : '群组' }}-->
<!--            </span>-->
          </el-option>
        </el-select>
      </wpwork-form-tip-item>

      <wpwork-form-tip-item label="任务负责人" prop="managers">
        <el-select
          v-model="dataForm.managers"
          placeholder="请选择任务负责人"
          multiple
          clearable
          :disabled="isSingleParticipant">
          <el-option
            v-for="user in personParticipants"
            :key="user.id"
            :label="user.realName"
            :value="user.id">
          </el-option>
        </el-select>
        <div v-if="isSingleParticipant" class="single-participant-tip">
          <i class="el-icon-info"></i>
          <span>参与人唯一，自动设为负责人</span>
        </div>
        <div v-if="hasGroupParticipants" class="group-participant-tip">
          <i class="el-icon-warning"></i>
          <span>包含群组参与人，请从个人参与人中选择负责人</span>
        </div>
      </wpwork-form-tip-item>

    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">{{$t('common.cancelButton')}}</el-button>
      <el-button type="primary" :loading="btnLoading" @click="dataFormSubmit()">
        {{$t('common.confirmButton')}}</el-button>
    </span>
    <UserBindPanel ref="userBindPanel" @user-selected="handleUserSelected"></UserBindPanel>
  </el-dialog>
</template>

<script>
import UserBindPanel from "./UserBindPanel.vue";
import { addGroup } from "@/api/group";

export default {
  components: { UserBindPanel },
  data() {
    return {
      visible: false,
      formLoading: false,
      btnLoading: false,
      dataForm: {
        taskTitle: "",
        taskContent: "",
        timeRange: [],
        participants: [], // 存储完整的用户对象
        managers: [] // 存储负责人用户ID
      },
      dataRule: {
        taskTitle: [{ required: true, message: "任务标题不能为空", trigger: "blur" }],
        taskContent: [{ required: true, message: "任务内容不能为空", trigger: "blur" }],
        timeRange: [{ required: true, message: "任务有效期不能为空", trigger: "change" }],
        participants: [{ required: true, message: "请选择任务参与人", trigger: "change" }],
        managers: [{ required: true, message: "请选择任务负责人", trigger: "change" }]
      }
    };
  },
  computed: {
    // 检查是否只有一个参与人
    isSingleParticipant() {
      return this.dataForm.participants.length === 1;
    },
    // 获取个人类型的参与人（负责人只能从个人中选择）
    personParticipants() {
      return this.dataForm.participants.filter(user => user.type === 'person');
    },
    // 检查是否包含群组参与人
    hasGroupParticipants() {
      return this.dataForm.participants.some(user => user.type === 'group');
    }
  },
  watch: {
    // 监听参与人变化，自动设置负责人
    'dataForm.participants': {
      handler(newParticipants) {
        const personParticipants = newParticipants.filter(user => user.type === 'person');

        if (personParticipants.length === 1) {
          // 只有一个个人参与人时，自动设为负责人
          this.dataForm.managers = [personParticipants[0].id];
        } else if (personParticipants.length === 0) {
          // 没有个人参与人时清空负责人
          this.dataForm.managers = [];
        }
        // 多个参与人时，保持原有的负责人选择，但过滤掉不在当前参与人列表中的负责人
        this.dataForm.managers = this.dataForm.managers.filter(managerId =>
          personParticipants.some(user => user.id === managerId)
        );
      },
      deep: true
    }
  },
  methods: {
    // 打开用户选择面板
    openUserBindPanel() {
      this.$refs.userBindPanel.init();
    },

    // 处理从UserBindPanel返回的用户选择
    handleUserSelected(users) {
      console.log('handleUserSelected:', users)
      this.dataForm.participants = users;

      // 过滤负责人，只保留仍在参与人列表中的个人负责人
      this.dataForm.managers = this.dataForm.managers.filter(managerId =>
        users.some(user => user.id === managerId && user.type === 'person')
      );
    },

    // 初始化对话框
    init() {
      this.dataForm = {
        taskTitle: "",
        taskContent: "",
        timeRange: [],
        participants: [],
        managers: []
      };
      this.visible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },

    // 提交表单
    dataFormSubmit() {
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          this.btnLoading = true;

          // 分离个人和群组参与人
          const personParticipants = this.dataForm.participants.filter(user => user.type === 'person');
          const groupParticipants = this.dataForm.participants.filter(user => user.type === 'group');

          // 构造任务数据
          const taskData = {
            userIds: personParticipants
              .filter(user => !this.dataForm.managers.includes(user.id))
              .map(user => user.id), // 普通个人用户（排除负责人）
            managerIds: this.dataForm.managers, // 负责人（只能是个人）
            groupIds: groupParticipants.map(group => group.id), // 群组ID
            type: "协同任务",
            text: this.dataForm.taskTitle,
            executionDate: this.dataForm.timeRange[1] ? new Date(this.dataForm.timeRange[1]) : null,
            begindate: this.dataForm.timeRange[0] ? new Date(this.dataForm.timeRange[0]) : null,
            enddate: this.dataForm.timeRange[1] ? new Date(this.dataForm.timeRange[1]) : null,
            jobinfo: JSON.stringify({
              option1: {
                notes: this.dataForm.taskTitle,
                body: this.dataForm.taskContent,
                value: "任务反馈",
                isphoto: "否"
              }
            }),
            location: "",
            resourcesId: this.generateResourceId()
          };

          // 调用API
          addGroup(taskData).then(res => {
            if (res.code === 200 || res.success) {
              this.$message({
                message: '协同任务创建成功',
                type: "success",
                duration: 1500,
                onClose: () => {
                  this.visible = false;
                  this.btnLoading = false;
                  this.$emit("refreshDataList");
                }
              });
            } else {
              this.$message.error(res.msg || '创建任务失败');
              this.btnLoading = false;
            }
          }).catch(error => {
            console.error('创建任务失败:', error);
            this.$message.error('创建任务失败');
            this.btnLoading = false;
          });
        }
      });
    },

    // 生成资源ID
    generateResourceId() {
      return 'task-' + Date.now() + '-' + Math.random().toString(36).substr(2, 9);
    }
  }
};
</script>

<style lang="scss" scoped>
.single-participant-tip {
  margin-top: 5px;
  font-size: 12px;
  color: #67C23A;
  display: flex;
  align-items: center;

  i {
    margin-right: 4px;
  }
}

.group-participant-tip {
  margin-top: 5px;
  font-size: 12px;
  color: #E6A23C;
  display: flex;
  align-items: center;

  i {
    margin-right: 4px;
  }
}

// 调整选择框样式
::v-deep .el-select {
  width: 100%;
}

// 只读选择框的样式调整
::v-deep .el-select.readonly {
  .el-input__inner {
    background-color: #f5f7fa;
    border-color: #e4e7ed;
    color: #c0c4cc;
    cursor: not-allowed;
  }
}
</style>
